package com.baocai.tools.netty.demo1;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;


public class ServerHandler extends ChannelInboundHandlerAdapter {


    private int counter;

    //演示半包读写  客户端发送了十次，但服务端会把十次都粘包，最后体现只收到一次
//    @Override
//    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
//
//        ByteBuf buf = (ByteBuf)msg;
//        byte[] bytes = new byte[buf.readableBytes()];
//        buf.readBytes(bytes);
//
//        String body = new String(bytes,"UTF-8").
//                substring(0,bytes.length - System.getProperty("line.separator").length());
//
//        System.out.println("服务端收到消息内容为：" + body + ", 收到消息次数：" + ++counter);
//
//    }


    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        String body = (String) msg;
        System.out.println("服务端收到消息内容为：" + body + ", 收到消息次数：" + ++counter);

    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }


}
